package com.fdb.efp.nls.api.rest;

import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.vo.UserInfo;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.efp.nls.common.FileDataConstant;
import com.fdb.efp.nls.common.UploadFileEnum;
import com.fdb.efp.nls.common.bo.UpLoadFileVO;
import com.fdb.efp.nls.service.facade.ImageBizDetailService;
import com.fdb.efp.nls.service.facade.UpLoadFileService;
import com.sunyard.CodeUtil;
import com.sunyard.client2.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class UpLoadFileController extends AbstractController {

	@Autowired
	@Qualifier("upLoadFileService")
	private UpLoadFileService upLoadFileService;
	
	@Autowired
	@Qualifier("imageBizDetailService")
	private ImageBizDetailService imageBizDetailService;
	
	/**
	 * 上传文件至影像平台
	  * @param vo
	  * @return
	  * @author heyingfeng
	  * @since 2019年1月17日 下午8:37:32
	  * @version 1.0
	 */
	@RequestMapping(value = "/up/load/file", method = RequestMethod.POST)
	public @ResponseBody
    ResponseData<Integer> uploadFile(@RequestBody UpLoadFileVO vo) {
		int outputVo = 0;
		String date = vo.getStartDate();
		vo.setStartDate(DateUtility.format10To8(date));
		outputVo = upLoadFileService.testUp(vo);
		return getResponseData(outputVo);
	}

	/**
	 * 查询批次信息(参数必须流水号)
	  * @param vo
	  * @return
	  * @author heyingfeng
	  * @since 2019年1月17日 下午8:35:38
	  * @version 1.0
	 */
	@RequestMapping(value = "/query/batch/file", method = RequestMethod.POST)
	public @ResponseBody
    ResponseData<String> queryBatchFile(@RequestBody UpLoadFileVO vo) {
		/*String contentId = "";
		String startDate = "";
		String dataFile = "";// 如需要查询单个文件，赋值文件属性
		if (Objects.nonNull(vo)) {
			startDate = vo.getStartDate();
			dataFile = vo.getImageType();// 如需要查询单个文件，赋值文件属性
		}
		List<UpLoadFileVO> outputVo = upLoadFileService.queryUploadFile(vo);
		contentId = outputVo.get(0).getBatch(); 
		startDate = outputVo.get(0).getStartDate(); 
		vo.setBatch(contentId);
		vo.setStartDate(startDate);
		vo.setImageType(dataFile);*/
		
		String ret = "";
		String date =  vo.getStartDate();
		vo.setStartDate(DateUtility.format10To8(date));
		ret = upLoadFileService.testQuery(vo);
		return getResponseData(ret);
	}
	
	/**
	 * 追加文件
	  * @param vo
	  * @return
	  * @author heyingfeng
	  * @since 2019年1月17日 下午8:38:06
	  * @version 1.0
	 */
	@RequestMapping(value = "/update/batch/file", method = RequestMethod.PUT)
	public @ResponseBody
    ResponseData<Integer> updateBatchFile(@RequestBody UpLoadFileVO vo) {
		/*String contentId = "";
		String startDate = "";
		int outputVo = 0;
		List<UpLoadFileVO> liatVo = upLoadFileService.queryUploadFile(vo);
		
		contentId = liatVo.get(0).getBatch();//查询批次号
		startDate = liatVo.get(0).getStartDate();//查询流水生成时间
		vo.setBatch(contentId);
		vo.setStartDate(startDate);*/
		
		vo.setStartDate(DateUtility.format10To8(vo.getStartDate()));
		int outputVo = upLoadFileService.testAdd(vo);//追加文件
		return getResponseData(outputVo);
	}
	
	/**
	 * 下载文件
	  * @param vo
	  * @return
	  * @author heyingfeng
	  * @since 2019年1月17日 下午8:38:06
	  * @version 1.0
	 */
	@RequestMapping(value = "/query/and/download", method = RequestMethod.POST)
	public @ResponseBody
    ResponseData<String> queryAndDownload(@RequestBody UpLoadFileVO vo) {
		/*String contentId = "";
		String startDate = "";
		String ret = "";
		String resultMsg = "";
		String index = "1";
		String dataFile = vo.getImageType();//如需要查询单个文件，赋值文件属性
		List<UpLoadFileVO> liatVo = upLoadFileService.queryUploadFile(vo);
		contentId = liatVo.get(0).getBatch();//查询批次号
		startDate = liatVo.get(0).getStartDate();//查询流水生成时间
		vo.setBatch(contentId);
		vo.setStartDate(startDate);
		vo.setImageType(dataFile);*/
		
		String ret = "";
		String date =  vo.getStartDate();
		vo.setStartDate(DateUtility.format10To8(date));
		String resultMsg = upLoadFileService.testQuery(vo);
		ret = upLoadFileService.testDown(vo, resultMsg, UploadFileEnum.ImageDeal.DOWNLOAN.getValue());//下载文件，index = 1为下载
		return getResponseData(ret);
	}
	
	/**
	 * 根据业务流水号查询数据
	 * @author  qiuyf
	 * @since 2019年3月18日 下午3:04:52
	 * @version 0.1 初始为0.1,后续变更则修改
	 */
	@RequestMapping(value = "/query/up/load/files", method = RequestMethod.POST)
	public @ResponseBody
    ResponseData<List<UpLoadFileVO>> queryUpLoadFiles(@RequestBody UpLoadFileVO vo) {
		List<UpLoadFileVO> outputVo = upLoadFileService.qryInfosByApplySeq(vo);
		// 对上传状态做转化、格式化进件日期
		outputVo.forEach(item -> {
			if(UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getState()) || UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getAddFileState())) {
				item.setState("成功");
			}else if(UploadFileEnum.UpLoadState.FAIL.getValue().equals(item.getState()) || UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getAddFileState())) {
				item.setState("失败");
			}
			if(StringUtil.isStrNotEmpty(item.getStartDate())) {
				item.setStartDate(DateUtility.format8To10(item.getStartDate()));
			}
		});
		return getResponseData(outputVo);
	}
	
	/**
	 * 上传影像平台信息列表查询
	 * @author  qiuyf
	 * @since 2019年4月2日 上午10:03:32
	 * @version 0.1 初始为0.1,后续变更则修改
	 */
	@RequestMapping(value = "/query/up/load/fileLists", method = RequestMethod.POST)
	public @ResponseBody
    ResponseData<List<UpLoadFileVO>> queryUpLoadFileLists(@RequestBody UpLoadFileVO vo) {
		List<UpLoadFileVO> outputVo = upLoadFileService.queryUploadFile(vo);
		// 对上传状态做转化、格式化进件日期
		outputVo.forEach(item -> {
			if(UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getState()) || UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getAddFileState())) {
				item.setState("成功");
			}else if(UploadFileEnum.UpLoadState.FAIL.getValue().equals(item.getState()) || UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getAddFileState())) {
				item.setState("失败");
			}
			if(StringUtil.isStrNotEmpty(item.getStartDate())) {
				item.setStartDate(DateUtility.format8To10(item.getStartDate()));
			}
		});
		return getResponseData(outputVo);
	}
	
	/**
	 * 删除批次信息
	 * @author  qiuyf
	 * @since 2019年4月2日 上午11:03:51
	 * @version 0.1 初始为0.1,后续变更则修改
	 */
	@RequestMapping(value = "/delete/batch/file", method = RequestMethod.DELETE)
	public @ResponseBody
    ResponseData<Integer> deleteBatchFile(@RequestBody UpLoadFileVO vo) {
		vo.setStartDate(DateUtility.format10To8(vo.getStartDate()));
		int outputVo = upLoadFileService.testDelete(vo);
		return getResponseData(outputVo);
	}

    /**
     * 根据产品编号/业务流水号查询数据
     * @author  ludayong
     * @since 【2020/5/7 15:15】
     * @version 0.1 初始为0.1,后续变更则修改
     */
    @RequestMapping(value = "/query/image/platfrom/files", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<UpLoadFileVO>> queryImagePlatfromInfo(@RequestBody UpLoadFileVO vo) {
		// 用户信息
		UserInfo userInfo = getUserInfo();
		// 影像信息
    	List<UpLoadFileVO> outputVo = null;
        try {
            outputVo = Optional.ofNullable(upLoadFileService.queryForImgSys(vo.getPrdCode(),vo.getApplySeq(),new ArrayList<String>())).orElseGet(ArrayList::new);
            // 对上传状态做转化、格式化进件日期
            outputVo.forEach(item -> {
            	// 设置产品编号
                item.setPrdCode(vo.getPrdCode());
                if(UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getState()) || UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getAddFileState())) {
					// 设置影像平台信息
					item = setImagePlatfrom(item);
                	item.setState("成功");
                }else if(UploadFileEnum.UpLoadState.FAIL.getValue().equals(item.getState()) || UploadFileEnum.UpLoadState.SUCCESS.getValue().equals(item.getAddFileState())) {
                    item.setState("失败");
                }
                if(StringUtil.isStrNotEmpty(item.getStartDate())) {
                    item.setStartDate(DateUtility.format8To10(item.getStartDate()));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getResponseData(outputVo);
    }

    /**
     * 根据业务流水号获取影像平台链接
     * @author  ludayong
     * @since 【2020/5/7 8:37】
     * @version 0.1 初始为0.1,后续变更则修改
     */
    @RequestMapping(value = "/query/image/platfrom/info", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<UpLoadFileVO> queryUpLoadUrl(@RequestBody UpLoadFileVO vo) {
		vo = setImagePlatfrom(vo);
        return getResponseData(vo);
    }

    /**
     * 将url参数加密
     * @param vo
     * @return
     */
    @RequestMapping(value = "/doEncode", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<String> doEncodeParam(@RequestBody UpLoadFileVO vo) {
        vo = setImagePlatfrom(vo);
        String encodeStr = "";

        String paramStr ="UID="+ vo.getImagePlatfromUserName()+"&PWD="+vo.getImagePlatfromPassWord()
                + "&AppID="+vo.getImagePlatfromAppId() + "&UserID="+vo.getSessionUserId()+"&UserName="+vo.getSessionUserName()
                + "&OrgID="+vo.getSessionOrgCode()+"&OrgName="+vo.getSessionOrgName()+"&info1=BUSI_SERIAL_NO:"+vo.getApplySeq()
                + ";OBJECT_NAME:"+vo.getImagePlatfromModelCode()+";QUERY_TIME:"+vo.getStartDate()+";FILELEVEL:1;RIGHT:"+vo.getRightCode();

        try {
            encodeStr = CodeUtil.encode(paramStr);
        }catch (Exception e){
            return ResponseData.create(encodeStr, ApplicationConstance.FAILURE,"参数加密失败",false);
        }
        return ResponseData.create(vo.getImagePlatfromUrl()+"?"+encodeStr, ApplicationConstance.SUCCESS,"参数加密成功",true);
    }

	/**
	 * 设置影像平台信息
	 * @author  ludayong
	 * @since 【2020/5/7 15:50】
	 * @version 0.1
	 */
	private UpLoadFileVO setImagePlatfrom(UpLoadFileVO upLoadFileVO){
		if (Objects.isNull(upLoadFileVO)){
			return null;
		}
		if (!Client.isInit) {
			Client.init();
		}
		// 影像平台url
		upLoadFileVO.setImagePlatfromUrl(Client.url);
		// 影像平台用户名
		upLoadFileVO.setImagePlatfromUserName(Client.userName);
		// 影像平台用户密码
		upLoadFileVO.setImagePlatfromPassWord(Client.passWord);
		// 影像平台资料等级
		// 影像平台操作权限
		// 影像平台内容模型代码
		upLoadFileVO.setImagePlatfromModelCode(FileDataConstant.MODEL_CODE);
		// 影像平台网贷系统ID
		upLoadFileVO.setImagePlatfromAppId(FileDataConstant.APP_ID);
		return upLoadFileVO;
	}
}
